<template>
	<div class="pagination">
		<button :disabled="pageNo <= 1" @click="$emit('changePageNo', pageNo - 1)">
			上一页
		</button>
		<button
			v-show="continueStartEnd.start > 1"
			@click="$emit('changePageNo', 1)"
		>
			1
		</button>
		<button v-show="continueStartEnd.start > 2">···</button>

		<button
			v-for="page in continuePagesArr"
			:class="{ active: page === pageNo }"
			@click="$emit('changePageNo', page)"
		>
			{{ page }}
		</button>

		<button v-show="continueStartEnd.end < totolPages - 1">···</button>
		<button
			v-show="continueStartEnd.end < totolPages"
			@click="$emit('changePageNo', totolPages)"
		>
			{{ totolPages }}
		</button>
		<button
			:disabled="pageNo === totolPages"
			@click="$emit('changePageNo', pageNo + 1)"
		>
			下一页
		</button>
	</div>
</template>

<script>
export default {
	name: "Pagination",
	props: ["totolPages", "continuePages", "pageNo"],
	computed: {
		continueStartEnd() {
			const { totolPages, continuePages, pageNo } = this;
			//先定义两个值 一个是连续页的起始值 一个是连续页的结束值
			let start = 0,
				end = 0;

			if (continuePages > totolPages) {
				start = 1;
				end = totolPages;
			} else {
				//1.首先根据当前页(pageNo)和连续页(continuePages)计算出基础的start和end
				//连续页一定是一个奇数, 连续页/2 然后向下取整 就得到了向前和向后推的页码数量
				start = pageNo - Math.floor(continuePages / 2);
				end = pageNo + Math.floor(continuePages / 2);

				//2. 判断：连续页的的起始如果小于1，则直接让连续页的起始变成1,然后对应的修改结束页
				if (start < 1) {
					start = 1;
					end = continuePages;
				}
				//3. 判断：连续页的结束如果大于总页数,则直接让连续页的结束变成总页数,然后对象的修改起始页
				if (end > totolPages) {
					end = totolPages;
					start = totolPages - continuePages + 1;
				}
			}

			// console.log(start, end);
			//返回连续页的两个值组成的对象
			return { start, end };
		},

		//计算得到符合条件的值:连续页的页码组成的数组
		continuePagesArr() {
			//已知结束页是 continueStartEnd.end
			//已知条件是 continueStartEnd.start
			//直接设置一个数组,把符合条件的值放在数组中
			const { start, end } = this.continueStartEnd;
			const arr = [];
			for (let i = 1; i <= end; i++) {
				if (i >= start) {
					arr.push(i);
				}
			}

			return arr;
		},
	},
};
</script>

<style lang="less" scoped>
.pagination {
	button {
		margin: 0 5px;
		background-color: #f4f4f5;
		color: #606266;
		outline: none;
		border-radius: 2px;
		padding: 0 4px;
		vertical-align: top;
		display: inline-block;
		font-size: 13px;
		min-width: 35.5px;
		height: 28px;
		line-height: 28px;
		cursor: pointer;
		box-sizing: border-box;
		text-align: center;
		border: 0;

		&[disabled] {
			color: #c0c4cc;
			cursor: not-allowed;
		}

		&.active {
			cursor: not-allowed;
			background-color: #409eff;
			color: #fff;
		}
	}
}
</style>
